
import React, { useRef } from 'react';
import type {
    ProFormInstance,
} from '@ant-design/pro-form';
import type { ModalProps } from 'antd';
import { message } from 'antd';
import styles from '../index.less';
import {
    postApiCrontab as Create,
    putApiCrontabById as Update,
    getApiCrontabCheckInstance as CheckInstance,
} from '@/services/furion-cms/crontab';
import ProForm, { ModalForm, ProFormSelect, ProFormSwitch, ProFormTextArea } from '@ant-design/pro-form';
import Cron from '@/components/CronBuilder';
import { useIntl } from 'umi';

interface DetailProps {
    modalVisible?: boolean;
    recored?: API.CrontabDetailDto;
    jobInstances?: API.EnumOptionDto[];
    onUpdate?: () => void;
    onVisibleChange: (visit: boolean) => void;
    modalProps?: Omit<ModalProps, 'visible'>;
}

const CrontabDetail: React.FC<DetailProps> = (props) => {
    const { modalVisible, onUpdate, onVisibleChange, modalProps, recored, jobInstances } = props;

    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();
    // 绑定一个 ProFormInstance 实例
    const formRef = useRef<ProFormInstance<API.CrontabDetailDto>>();

    const finishHandle = async (values: any) => {
        console.log('finishHandle', values);
        // 提交成功处理
        const successHandle = () => {
            // 清空数据
            message.success('任务信息保存成功');
            onUpdate?.();
            return true;
        }

        if (recored?.id) {
            // 更新
            return Update({ id: recored?.id }, { ...values })
                .then(successHandle);
        }
        else {
            // 创建
            return Create({ ...values })
                .then(successHandle);
        }
    };

    return (
        <ModalForm<API.CrontabDetailDto>
            title={intl.formatMessage({
                id: recored?.id ? 'pages.crontab.detail.editer' : 'pages.crontab.detail.create',
                defaultMessage: recored?.id ? '编辑任务' : '创建任务'
            })}
            formRef={formRef}
            className={styles.detail}
            modalProps={{
                destroyOnClose: true,
                width: 450,
                maskClosable: false,
                ...modalProps
            }}
            visible={modalVisible}
            initialValues={recored}
            onFinish={finishHandle}
            onVisibleChange={onVisibleChange}
        >
            <ProFormSelect
                name="instancePath"
                label={intl.formatMessage({
                    id: 'pages.crontab.detail.instancePath',
                    defaultMessage: '任务实例'
                })}
                tooltip={intl.formatMessage({
                    id: 'pages.crontab.detail.instancePath.tooltip',
                    defaultMessage: '任务实例只允许存在一个'
                })}
                validateTrigger={['onChange', 'onBlur']}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: 'pages.crontab.detail.instancePath.required',
                            defaultMessage: '请选择任务实例'
                        }),
                        validateTrigger: 'onChange',
                    },
                    {
                        validator: async (_, value) => {
                            if (value) {
                                const { success, errorMessage } = await CheckInstance({
                                    path: value,
                                    id: recored?.id
                                }, { skipErrorHandler: true })
                                if (!success) {
                                    return Promise.reject(errorMessage);
                                }
                                return Promise.resolve();
                            }
                            else {
                                return Promise.resolve();
                            }
                        },
                        validateTrigger: 'onBlur'
                    }
                ]}
                request={() => Promise.resolve(jobInstances ?? [])}
            />
            <ProForm.Item name="cronExpression"
                label={intl.formatMessage({
                    id: 'pages.crontab.detail.cronExpression',
                    defaultMessage: '任务计划'
                })}
                tooltip={intl.formatMessage({
                    id: 'pages.crontab.detail.cronExpression.tooltip',
                    defaultMessage: 'Cron 表达式，支持6个域值自定义'
                })}
                className={styles.cron}
                rules={[
                    {
                        required: true,
                        message: intl.formatMessage({
                            id: 'pages.crontab.detail.cronExpression.required',
                            defaultMessage: '请配置任务计划'
                        }),
                    },
                    {
                        validator: async (_, value) => {
                            console.log('cronExpression', value);
                            if (value) {
                                const cronElements = value.split(' ');
                                if (cronElements.length !== 6) {
                                    return Promise.reject(intl.formatMessage({
                                        id: 'pages.crontab.detail.cronExpression.requiredError',
                                        defaultMessage: 'cron表达式只支持6个域值'
                                    }));
                                }
                                return Promise.resolve();
                            }
                            return Promise.resolve();
                        },
                    }
                ]}>
                <Cron multiple />
            </ProForm.Item>
            <ProFormTextArea name="description"
                label={intl.formatMessage({
                    id: 'pages.crontab.detail.description',
                    defaultMessage: '任务描述'
                })}
            />
            <ProFormSwitch name="enable"
                label={intl.formatMessage({
                    id: 'pages.crontab.detail.enable',
                    defaultMessage: '是否启用'
                })}
                tooltip={intl.formatMessage({
                    id: 'pages.crontab.detail.enable.tooltip',
                    defaultMessage: '若当前任务正在运行,更改将导致任务被停止'
                })} />
        </ModalForm>
    )
}

export default CrontabDetail;